package com.cositas.dulces.lp.promo2012;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Coupon;
import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class EnterCouponAction implements Action {
	

	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		String code = req.getParameter(Coupon.field_code);
		String fbid = req.getParameter(Participant.field_fbid);
		if (code == null || code.trim().length() == 0) {
			req.getRequestDispatcher("./ups.jsp").forward(req, resp);
			return;
		}
		Key couponKey = KeyFactory.createKey(Coupon.entity_name, code);
		Key participantKey = KeyFactory.createKey(Participant.entity_name, fbid);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		try {
			Entity coupon = datastore.get(couponKey);
			Entity participant = datastore.get(participantKey);
			
			Boolean shared = (Boolean)coupon.getProperty(Coupon.field_shared);
			String reminderSt = (String)coupon.getProperty(Coupon.field_remainder);
			Integer remainder = Integer.valueOf(reminderSt);
			
			if (remainder > 0) { // si quedan
				Collection<String> usedBy = (Collection<String>)coupon.getProperty(Coupon.field_fbids);
				if (usedBy == null) {
					usedBy = new ArrayList<String>();
				}
				if (usedBy.contains(fbid)) {
					req.getRequestDispatcher("./cuponYaCargado.jsp").forward(req, resp);
				} else {
					Integer points = Integer.valueOf((String)coupon.getProperty(Coupon.field_points));
					Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
					account = account + points;
					participant.setProperty(Participant.field_points, account.toString());
					datastore.put(participant);
					usedBy.add(fbid);
					coupon.setProperty(Coupon.field_remainder, String.valueOf(remainder.intValue() - 1));
					coupon.setProperty(Coupon.field_fbids, usedBy);
					datastore.put(coupon);
					req.getRequestDispatcher("./couponSuccess.jsp").forward(req, resp);
				}
			} else {
				if (shared) {
					req.getRequestDispatcher("./cuponAgotado.jsp").forward(req, resp);
				} else {
					req.getRequestDispatcher("./ups.jsp").forward(req, resp);
				}
			}
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
			req.getRequestDispatcher("./ups.jsp").forward(req, resp);
		}
	}
}
